package com.onlyxiahui.aware.extend.shardingsphere.algorithm;

import java.util.Collection;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import com.onlyxiahui.aware.extend.shardingsphere.algorithm.util.ShardingHandlerUtil;

/**
 * Long 取模<br>
 * Date 2019-08-26 10:57:11<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class ModulusLongPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

	@Override
	public String doSharding(
			final Collection<String> databaseNames,
			final PreciseShardingValue<Long> shardingValue) {

		// 当前数据节点数量
		int size = databaseNames.size();
		if (size == 1) {
			return databaseNames.iterator().next();
		}

		Long value = shardingValue.getValue();
		// 计算当前分片值所在的节点号
		long nodeNumber = Math.floorMod(value, Long.parseLong(size + ""));
		// 找到匹配的数据库名称并返回
		for (String databaseName : databaseNames) {
			if (ShardingHandlerUtil.eq(databaseName, nodeNumber)) {
				return databaseName;
			}
		}
		throw new RuntimeException("数据分片异常");
	}
}
